/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.aapl.annotation.strategy;

import org.apache.ibatis.aapl.annotation.FieldInjection;
import org.apache.ibatis.aapl.annotation.impl.FieldInjectionStrategy;
import org.apache.ibatis.aapl.registry.SqlMethod;
import org.apache.ibatis.aapl.util.ReflectUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gu
 * @date 2020/3/30 11:20
 */
public class FieldInjectionStrengthener implements BeforeAnnotationStrengthener {

  private Map<Class<? extends FieldInjectionStrategy>, FieldInjectionStrategy> strategyMap = new HashMap<>(4);

  @Override
  public void strengthen(Object object, SqlMethod method) {
    FieldInjection annotation = method.getMethod().getAnnotation(FieldInjection.class);
    if (annotation == null) {
      return;
    }
    if (annotation.props().length != annotation.strategies().length) {
      System.out.println("注解字段与策略长度不一致，停止增强");
      return;
    }
    doStrengthen(object, annotation);
  }

  private void doStrengthen(Object object, FieldInjection injection) {
    String[] props = injection.props();
    Class<? extends FieldInjectionStrategy>[] strategies = injection.strategies();
    for (int i = 0; i < props.length; i++) {
      String prop = props[i];
      Class<? extends FieldInjectionStrategy> strategyClazz = strategies[i];
      Method setMethod = ReflectUtil.getSetMethod(object, prop);
      FieldInjectionStrategy fieldInjectionStrategy = strategyMap.computeIfAbsent(strategyClazz, k -> {
        try {
          return strategyClazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          e.printStackTrace();
        }
        return null;
      });
      if (fieldInjectionStrategy != null) {
        Object value = fieldInjectionStrategy.getValue();
        try {
          setMethod.invoke(object, value);
        } catch (IllegalAccessException | InvocationTargetException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
